package com.example.myblog.controller;

import com.example.myblog.domain.User;
import com.example.myblog.service.user.UserServiceImpl;
import com.example.myblog.util.COOKIEUtil;
import com.example.myblog.util.MD5;
import com.example.myblog.util.SendMail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.naming.spi.DirStateFactory;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Result;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Logger;

/**
 * @Author: Wu YunXia
 * @Description: 用户
 * @Date: Created in 10:12 2020/11/26
 * @Modefied By:
 */
@RestController
public class UserController {

    @Resource
    HttpServletRequest request;
    @Resource
    HttpServletResponse response;


    @Resource
    UserServiceImpl userService;

    @Autowired
    SendMail sendMail;



    /**
    * @desc: 注册
    */
    @RequestMapping(value = "/user/register",method = RequestMethod.POST)
    public Object register(@RequestBody User user){
        String username = user.getUsername();
        String password = user.getPassword();
        String email = user.getEmail();

        System.out.println("username:"+username);
        System.out.println("email:"+email);

        String uuid = UUID.randomUUID().toString();//转化为String对象
        uuid = uuid.replace("-","");//去掉-

        Map map = new HashMap();

        user.setUuid(uuid);
        user.setState("0");

        if(username!=null && password!=null && email!=null){

            List<User> emailList = userService.queryForEmail(email);//查询邮箱
            List<User> userList = userService.queryForUsername(username);//查询用户名是否存在

            if(userList.size()!=0){
                map.put("code",-1);
                map.put("msg","用户名已存在");

            }else if(emailList.size()!=0){
                map.put("code",-1);
                map.put("msg","邮箱已存在");

            }else{
                int isRegister = userService.register(user);
                if(isRegister>0){
                    sendMail.send(uuid,email);
                    map.put("code",200);
                    map.put("msg","注册成功,激活链接已发到邮箱，请前往激活");
                }else{
                    sendMail.send(uuid,email);
                    map.put("code",-1);
                    map.put("msg","注册失败");
                }
            }
        }else{
            map.put("code",-1);
            map.put("msg","账号密码邮箱不能为空");
        }
        return map;
    }


@RequestMapping("/responseEntity.do")
public ResponseEntity responseEntity(){
    Map<String,Object> map = new HashMap<String,Object>();
    map.put("message", "Hello Wrold");
    return new ResponseEntity(map, HttpStatus.OK);
}


    /**
     * @desc: 改变state (是否激活账号) 激活邮件
     */
    @RequestMapping("/user/activeEmail")
    public String changeState(@RequestParam String uuid){
        String msg = "激活失败";
        int state = userService.activeEmail(uuid);
        if(state>0){
            msg = "账号已激活";
        }
        return msg;
    }



//
/**
    * @desc: 登录
    */
    @RequestMapping(value = "/user/login",method = RequestMethod.POST)
    public Object login(@RequestBody User user){


        Map map = new HashMap();
        String username = user.getUsername();
        String password = user.getPassword();

        if(username!=null && password!=null){
            List<User> userList = userService.login(username);
            if(userList.size()!=0){
                String uuid = userList.get(0).getUuid();
                String email = userList.get(0).getEmail();

                String password1 = userList.get(0).getPassword();
                if(userList.get(0).getState().equals("1")){
                    if(password.equals(password1)){
                        //添加cookie
                        COOKIEUtil.addCookie(response,uuid,username,3600);

                        map.put("id",userList.get(0).getId());
                        map.put("username",userList.get(0).getUsername());
                        map.put("email",userList.get(0).getEmail());
                        map.put("code",200);
                        map.put("msg","登录成功");
                    }else{
                        map.put("code",-1);
                        map.put("msg","密码错误");
                    }
                }else{
                    sendMail.send(uuid,email);
                    map.put("code",-1);
                    map.put("msg","账号暂未激活，请前往激活");
                }
            }else{
                map.put("code",-1);
                map.put("msg","账号不存在");
            }
        }else{
            map.put("code",-1);
            map.put("msg","账号和密码不能为空");
        }
        return map;
    }


    /**
    * @desc: 重置密码
    */
    @RequestMapping("/user/resetPassword")
    public Object resetPassword(String email) throws Exception {
        List<User> userList = userService.queryForEmail(email);
        String random = "";
        for(int i = 0; i < 8; i ++){
//            random += Math.random()*6;
            int r = (int) Math.floor(Math.random() * 10);
            random += r;
        }


        String mdrandom = MD5.stringToMD5(random);

        String uuid = UUID.randomUUID().toString();//转化为String对象
        uuid = uuid.replace("-","");//去掉-
        System.out.printf("random:"+random);
        Map map = new HashMap();
        if(userList.size()==0) {
            map.put("code", -1);
            map.put("msg", "邮箱暂未注册");
        }else{

            int reset = userService.resetPass(email,mdrandom,uuid);

            if(reset>0){
                sendMail.updatePass(email,random);
                map.put("code", 200);
                map.put("msg", "密码已发至邮箱，请前往查看");
            }else{
                map.put("code", -1);
                map.put("msg", "未知错误");
            }

        }
        return map;
    }

    /**
    * @Date 9:44 2020/11/30
    * @desc: 修改密码
    */
    @RequestMapping(value = "/user/updatePassword",method = RequestMethod.POST)
    public Object updatePass(@RequestBody User user){

        Map map = new HashMap();

        int id = user.getId();

        String password = user.getPassword();

//        String newPassword = list.get(0).;

        String uuid = UUID.randomUUID().toString();//转化为String对象
        uuid = uuid.replace("-","");//去掉-


        //获取cookie
        Cookie c = COOKIEUtil.getCookieByName(request,"bUsername");

//        String uuid = c.getValue();
//        System.out.println("uuid:"+uuid);

        if(c==null){
            map.put("code",13);
            map.put("msg","请登录");

        }else if(id>0 && password!=null){

            List<User> userList = userService.queryId(id);
            if(userList.size()!=0){
                int rUid = userService.updatePass(id,password,uuid);
                if(rUid>0){
                    map.put("code",200);
                    map.put("msg","修改成功");
                }else{
                    map.put("code",-1);
                    map.put("msg","修改失败");
                }

            }else{
                map.put("code",-1);
                map.put("msg","用户不存在");
            }
        }else{
            map.put("code",-1);
            map.put("msg","用户和密码不能为空");
        }

        return map;
    }


    /**
    * @Date 14:00 2020/11/30
    * @desc:
    */
    @RequestMapping("/user/logout")
    public Object logout(String uuid){
        Map map = new HashMap();
        Cookie c = COOKIEUtil.getCookieByName(request,"bUsername");
        if(c!=null){
            if(c.getValue().equals(uuid)){
                boolean b = COOKIEUtil.delCookie(response,request,"bUsername");
                if(b){
                    map.put("code",200);
                    map.put("msg","退出成功");
                }else{
                    map.put("code",13);
                    map.put("msg","请登录");
                }
            }else{
                map.put("code",13);
                map.put("msg","请登录");
            }
        }else{
            map.put("code",13);
            map.put("msg","请登录");
        }


        return map;
    }



    @RequestMapping("/user/queryAll")
    public Object queryAll(){
        return userService.queryAll();
    }

}


//[{
////    name:"",
////        pay:int
////        }]
